package com.purchase.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.purchase.entity.User;
import com.purchase.entity.UserAddress;
import com.purchase.mapper.UserAddressMapper;
import com.purchase.mapper.UserMapper;
import com.purchase.service.UserService;
import com.purchase.util.AuthUtil;
import com.purchase.util.JavaWebToken;
import com.purchase.util.LogInfo;
import com.purchase.util.MyBeanUtils;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

	@Resource
	UserMapper userMapper;

	@Resource
	UserAddressMapper userAddressMapper;
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public ResponseForm addUer(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			User user = new User();
			MyBeanUtils.populate(user, paramMap);
			user.setCreateTime(new Date());
			if (!StringUtils.isNotBlank(user.getName())){
				result.setStatus(false);
				result.setMessage(LogInfo.USER_NAME_LOG);
				log.error(LogInfo.USER_NAME_LOG);
				return result;
			}
			if (!StringUtils.isNotBlank(user.getPassword())){
				result.setStatus(false);
				result.setMessage(LogInfo.USER_PASSWORD_LOG);
				log.error(LogInfo.USER_PASSWORD_LOG);
				return result;
			}
			userMapper.insertSelective(user);

			//result.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@Override
	public ResponseForm checkUerName(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			User user = new User();
			MyBeanUtils.populate(user, paramMap);
			//user.setName(String.valueOf(paramMap.get("name")));
			user = userMapper.selectOne(user);
			if(user!=null){
				result.setStatus(true);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_CHECK_LOG);
				log.error(LogInfo.USER_CHECK_LOG);
				return result;
			}
			result.setMessage(LogInfo.USER_CHECK_SUCCESS);
			result.setCode(LogInfo.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@Override
	public ResponseForm login(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			User user = new User();
			//MyBeanUtils.populate(user, paramMap);
			user.setName(String.valueOf(paramMap.get("name")));
			user.setStatus(0);
			user = userMapper.selectOne(user);
			if(user==null){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_ERROR);
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			if(!user.getPassword().endsWith(String.valueOf(paramMap.get("password")))){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.PASSWORD_ERROR);
				log.error(LogInfo.PASSWORD_ERROR);
				return result;
			}
			
			Map<String, Object> loginInfo = new HashMap<>();
            loginInfo.put("userId", user.getId());
            String sessionId = JavaWebToken.createJavaWebToken(loginInfo);
            System.out.println("sessionID"+sessionId);
            user.setSessionId(sessionId);
            
			result.setData(user);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public ResponseForm update(RequestForm param,HttpServletRequest request) {
		ResponseForm result = new ResponseForm();
		
		//登录认证
//		try {
//			Long userId = AuthUtil.getUserId(request);
//		} catch (Exception e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//			result.setStatus(false);
//			result.setCode("500");
//			result.setMessage(LogInfo.AUTH_ERROR);
//			log.error(LogInfo.AUTH_ERROR);
//			return result;
//		}
		
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			
			User user = new User();
			MyBeanUtils.populate(user, paramMap);
			//user.setName(String.valueOf(paramMap.get("name")));
			
			userMapper.updateByPrimaryKeySelective(user);
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@Override
	public ResponseForm getUserAddress(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String userId = (String) paramMap.get("userId");
			if(!StringUtils.isNotBlank(userId)){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_ERROR);
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			User user = userMapper.selectByPrimaryKey(Integer.valueOf(userId));
			if(user==null){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_LOG);
				log.error(LogInfo.USER_LOG);
				return result;
			}
			Example example  = new Example(UserAddress.class);
			example.setOrderByClause("default_options DESC");
			Criteria criteria=example.createCriteria();
			criteria.andEqualTo("userId", userId);
			criteria.andEqualTo("status", 0);
			List<UserAddress> list =userAddressMapper.selectByExample(example);
		   
			result.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public ResponseForm addUserAddress(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String userId = (String) paramMap.get("userId");
			if(!StringUtils.isNotBlank(userId)){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_ERROR);
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			User user = userMapper.selectByPrimaryKey(Integer.valueOf(userId));
			if(user==null){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_LOG);
				log.error(LogInfo.USER_LOG);
				return result;
			}
			UserAddress userAddress = new UserAddress();
			MyBeanUtils.populate(userAddress, paramMap);
		
			userAddress.setCreateTime(new Date());
			userAddressMapper.insertSelective(userAddress);
			
//			User user = new User();
//			MyBeanUtils.populate(user, paramMap);
//			//user.setName(String.valueOf(paramMap.get("name")));
//			userMapper.updateByPrimaryKeySelective(user);
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public ResponseForm updateUserAddress(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String userId = (String) paramMap.get("userId");
			
			if(!StringUtils.isNotBlank(userId)){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_ERROR);
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			User user = userMapper.selectByPrimaryKey(Integer.valueOf(userId));
			if(user==null){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_LOG);
				log.error(LogInfo.USER_LOG);
				return result;
			}
			
			
			
			UserAddress userAddress = new UserAddress();
			MyBeanUtils.populate(userAddress, paramMap);
			if(userAddress.getDefaultOptions()!=null && userAddress.getDefaultOptions()==1){
				userAddressMapper.updateDefaultOptions(Integer.valueOf(userId));
			}
			userAddressMapper.updateByPrimaryKeySelective(userAddress);
			//userAddressMapper.updateByExampleSelective(record, example)
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@Override
	public ResponseForm getUserAddressById(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String addressId = (String) paramMap.get("id");
			if(!StringUtils.isNotBlank(addressId)){
				result.setStatus(false);
				result.setCode(LogInfo.PARAM_ERROR);
				result.setMessage(LogInfo.USER_ERROR);
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			UserAddress userAddress = new UserAddress();
			MyBeanUtils.populate(userAddress, paramMap);
			userAddress=userAddressMapper.selectOne(userAddress);
			result.setData(userAddress);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@Override
	public ResponseForm listUser(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			User user = new User();
			//MyBeanUtils.populate(user, paramMap);
			String userId =String.valueOf(paramMap.get("userId"));
			user.setId(Integer.parseInt(userId));
			user.setStatus(0);
			user = userMapper.selectOne(user);
			if(user==null){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_ERROR);
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			if(user.getRoleId()!=2){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage("权限不够");
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			com.purchase.util.Page.parsePage(paramMap);
			
			Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
			
			Example example = new Example(User.class);
			example.createCriteria().andEqualTo("roleId", "1");
			List<User> userList = userMapper.selectByExample(example);
			result.setData(userList);
			result.setTotal((int) pageHelper.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@Override
	public ResponseForm getUserById(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			User user = new User();
			//MyBeanUtils.populate(user, paramMap);
			String userId =String.valueOf(paramMap.get("userId"));
			if(!StringUtils.isNotBlank(userId)){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			
			user.setId(Integer.parseInt(userId));
			user.setStatus(0);
			user = userMapper.selectOne(user);
			result.setData(user);
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@Override
	public ResponseForm listUserByStoreNo(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			User user = new User();
			//MyBeanUtils.populate(user, paramMap);
			String storeNo =String.valueOf(paramMap.get("storeNo"));
			String userId =String.valueOf(paramMap.get("userId"));
			user.setId(Integer.parseInt(userId));
			user.setStatus(0);
			user = userMapper.selectOne(user);
			if(user==null){
				result.setStatus(false);
				result.setCode(LogInfo.ERROR_CODE);
				result.setMessage(LogInfo.USER_ERROR);
				log.error(LogInfo.USER_ERROR);
				return result;
			}
			
			com.purchase.util.Page.parsePage(paramMap);
			
			Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
			
			Example example = new Example(User.class);
			example.createCriteria().andEqualTo("storeNo", storeNo).andEqualTo("roleId", 1);
			List<User> userList = userMapper.selectByExample(example);
			result.setData(userList);
			result.setTotal((int) pageHelper.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error(LogInfo.ERROR);
		}
		return result;
	}
}
